﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Reflection;

namespace Ruandao.MiniAccess
{
    /// <summary>
    /// </summary>
    public class DataSourceSetter
    {
        readonly static DataSourceSetter instance = new DataSourceSetter();

        static public DataSourceSetter Instance
        {
            get { return instance; }
        }

        /// <summary>
        /// 数组元素内有两个元素，依次为accessType和connectionString。
        /// </summary>
        Dictionary<string, string[]> providers = new Dictionary<string, string[]>();
        private DataSourceSetter()
        {
            //读出<dataProviders>中的所有提供者。
            MiniAccessSection section = (MiniAccessSection)ConfigurationManager.GetSection("miniAccess");
            foreach (ProviderElement p in (ProviderCollection)section.DataProviders)
            {
                string accessType = p.AccessType;
                string connectionString = p.ConnectionString;

                if ( !string.IsNullOrEmpty(p.DataSourceSetter) )
                {
                    IDataSourceSetter setter = (IDataSourceSetter)Activator.CreateInstance(Type.GetType(p.DataSourceSetter));
                    if( setter.GetAccessType() != "" )
                    {
                        accessType = setter.GetAccessType();
                        connectionString = setter.GetConnectionString();
                    }
                }
                providers.Add(p.Name, new string[] { accessType, connectionString });
            }
        }

        #region IDataSourceSetter 成员

        /// <summary>
        /// 
        /// </summary>
        /// <param name="providerName"></param>
        /// <returns></returns>
        public string GetAccessType(string providerName)
        {
            return providers[providerName][0];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="providerName"></param>
        /// <returns></returns>
        public string GetConnectionString(string providerName)
        {
            return providers[providerName][1];
        }

        #endregion
    }
}
